package com.cx.filter;
import com.cx.sources.DynamicTenantDataSources;
import com.cx.utils.constant.Constants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @Author cenxi
 * @Date 2023/8/16 14:26
 * @Version 1.0
 */
@Slf4j
@Component
public class CustomerEnableIntercept implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //保证只有controller方法被拦截
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        String tenantId = request.getHeader(Constants.TENANTID);
        if (StringUtils.isNotBlank(tenantId)) {
            DynamicTenantDataSources.setDataSource(DynamicTenantDataSources.DATA_SOURCE_BEAN_PREFIX + tenantId);
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) {
        DynamicTenantDataSources.clearDataSource();
    }

}
